function DetailProductController(){ }
DetailProductController.prototype.params = {};
    
$(function(){

    var innerParams;
    var currentData;
    
    $(document).on("pagebeforeshow","#pageItemList",function() {
        monaca.updateUIStyle("titlelable", "text", "商品詳細");
        monaca.updateUIStyle("backheader", "visibility", "true");
        monaca.updateUIStyle("footer", "visibility", "false");
        Util.prototype.changeSnapperElement("pageItemList-content");        
        DetailProductController.prototype.loadData();
    });
    
    $(document).on("pageshow","#pageItemList",function() {
        PageChangeController.prototype.freeMemory();  
        
    });
    
    DetailProductController.prototype.loadData = function() {
        $("#add-to-atodekau").hide();
        innerParams = DetailProductController.prototype.params;

        currentData = {};
        // console.log("barcode: " + innerParams.barcode_number + " eccode: " + innerParams.ecsite_code + " item: " + innerParams.item_id + " bm id: " + innerParams.id + ""  );
        /*new */
        checkData(function() {
            if(innerParams.searchKindAction == 0) { //barcode
                loadPageByBarcode(innerParams);
            } else if(innerParams.searchKindAction == 1) {
                loadPageByEcCodeAndItemId(innerParams);
            }
        });
    };
    
    function checkData(callbackLoadData) {
        if(typeof innerParams.barcode_number != "undefined" && innerParams.barcode_number != "") {
            innerParams.searchKindAction = 0; //barcode
            BookmarksService.prototype.getBmDataByBarcode(innerParams.barcode_number, function(results) {
                // console.log(JSON.stringify(results.rows));
                if(results.rows.length > 0) { // if existed
                    var row = results.rows.item(0);                    
                    innerParams.id = row.id;
                    // console.log("status: " + row.status);
                    innerParams.typeAction = row.status == 0 ? 1 : 0;
                } else { //if not
                    innerParams.typeAction = 2; //new
                }
                callbackLoadData();
            });
        } else if(typeof innerParams.ecsite_code != "undefined" &&  innerParams.ecsite_code != "" 
                 && typeof innerParams.item_id != "undefined" && innerParams.item_id != "") {
            innerParams.searchKindAction = 1; //Ecsite_code & Item_id         
            BookmarksService.prototype.getBookmarkByECsiteCodeAndItemId (innerParams.ecsite_code, innerParams.item_id, function(results) {                
                if(results.rows.length > 0) {  //if existed in bookmark table
                    innerParams.id = results.rows.item(0).id;
                    innerParams.typeAction = 0; //bookmarked
                } else {  // if not
                    innerParams.typeAction = 2; // New
                }
                callbackLoadData();
            });
            
        } else if(typeof innerParams.id != "undefined" && innerParams.id != "") {
            BookmarksService.prototype.getBookmarkObject(innerParams.id, function(results) {
                // if existed data in bookmark table 
                if(results.rows.length > 0) {
                    var row = results.rows.item(0);
                    
                    if(row.barcode_number != "") {
                        innerParams.barcode_number = row.barcode_number;
                        innerParams.searchKindAction = 0; //  barcode;
                    } else if(row.ecsite_code != "" && row.item_id != "") {
                        innerParams.ecsite_code = row.ecsite_code;
                        innerParams.item_id = row.item_id;
                        innerParams.searchKindAction = 1; //  ECsite_code and item_id       
                    }
                   
                    innerParams.typeAction = row.status == 0 ? 1 : 0;  // scanned or bookmarked 
//                    console.log("inner typeAction: " + innerParams.typeAction);
                    callbackLoadData();
                } else {
                    alert("Wrong bookmark id"); 
                    innerParams.searchKindAction = 404;
                    callbackLoadData();
                };
            });    
        } else {
            innerParams.searchKindAction = 404;
            callbackLoadData(); 
        }
    }
    
    function loadPageByBarcode(params) {
        var barcode_number = params.barcode_number;
        getDataByBarcode(barcode_number, function(dataItem) {
            currentData = {};
            currentData.dataItem = {};
            
            currentData.searchKindAction = params.searchKindAction;
            currentData.typeAction = params.typeAction;
            currentData.id = params.id;
            currentData.barcode_number = barcode_number;
            currentData.dataItem = dataItem;
            console.log("getDataByBarcode");
            if (typeof params.doScanAction != "undefined" && params.doScanAction) {
                saveScanData(currentData.id, barcode_number, dataItem, function(saveScanId) {
                    currentData.id = saveScanId;
                    console.log("cur id: " + saveScanId);
                    if(currentData.typeAction != 0) {
                        currentData.typeAction = 11; //just scan typeAction
                    }
                    params.doScanAction = null;
                    displayDetailProductPage(dataItem);
                    
                });
               
            } else {
                displayDetailProductPage(dataItem);
            }
        }, function(Ex) {
            displayNoResultData(barcode_number);
        });
    }
    
    function saveScanData(bmid, barcode, dataItem, callback) {
        var params = {};
        if (typeof bmid == 'undefined' || bmid == '') {
            params.status = 0;
        }
        params.saveLogType = DetailProductService.prototype.SERVER_LOG_SCAN;
        params.barcode_number = barcode;
        params.genre_code = dataItem.genre_code;
        params.item_name = dataItem.item_name;
        params.ecsite_code = "" + dataItem.ecsite_code;
        params.image_url = dataItem.image_url;
        params.registered_date = Util.prototype.getTodayObj().ymd;
        if(SettingService.prototype.isLocationAllow()) {
            ScanService.prototype.getScanAddress(function(callbackData) {
                params.longitude = callbackData.longitude;
                params.latitude = callbackData.latitude;
                params.prefecture_code = callbackData.prefecture_code;
                params.pref_no = callbackData.pref_no;
                BookmarksService.prototype.saveScanBookmark(bmid, params, callback);
            }, function() {
                BookmarksService.prototype.saveScanBookmark(bmid, params, callback);
            });
        } else {
            BookmarksService.prototype.saveScanBookmark(bmid, params, callback);
        }
    }
    
    function loadPageByEcCodeAndItemId(params) {
        getDataByECcodeAndItemId(params.ecsite_code, params.item_id, function(dataItem) {
            currentData = {};
            currentData.dataItem = {};
            currentData.ecsite_code = params.ecsite_code;
            currentData.item_id = params.item_id;
            currentData.searchKindAction = params.searchKindAction;
            currentData.typeAction = params.typeAction;
            currentData.id = params.id;
            currentData.dataItem = dataItem;
            displayDetailProductPage(dataItem);
        },function(Ex) {
            displayNoResultData();
        });
    }    

    function getDataByBarcode(barcode, callbackSuccess, callbackError) {
        var dataItem = {};
        var shopsdone = false, itemdone = false;
        DetailProductService.prototype.getItemInfo({action: "findbybarcode", barcode: barcode}, function(data) {            
            var items = data.items;
            if(items.length > 0) {
                dataItem.ECShop = [];                
                for(var i=0;i<items.length;i++) {
                    var params = {};
                    params.lowestPrice = items[i].formattedLowestPrice;
                    params.shop_name = items[i].lowestShopName;
                    params.shop_url = items[i].lowestShopUrl;
                    params.numberOfItems = items[i].numberOfItems;
                    params.ecsite_code = items[i].ecSiteCode;
                    dataItem.ECShop.push(params);
                } 
      
                dataItem.ecsite_code = dataItem.ECShop[0].ecsite_code;
                dataItem.shop_name = dataItem.ECShop[0].shop_name;
                dataItem.shop_url = dataItem.ECShop[0].shop_url;
                dataItem.lowestPrice = dataItem.ECShop[0].lowestPrice; 
                
                shopsdone = true;
                if (itemdone) {
                    callbackSuccess(dataItem);
                }
            }  else {
                callbackError('');
            }
        }, function(Ex) {
            callbackError(Ex);
        }); 
        
        DetailProductService.prototype.getItemInfo({action: "prodbybarcode", barcode: barcode}, function(data2) {
            dataItem.item_name = data2.productName;   
            dataItem.genre_code = data2.genreId;
            if(typeof data2.smallImageUrl != "undefinded" && data2.smallImageUrl != "") {
                dataItem.image_url = data2.smallImageUrl;
            } else {
                dataItem.image_url = Messages.prototype.NO_IMAGE;
            }
            
            itemdone = true;
            if (shopsdone) {
                callbackSuccess(dataItem);
            }
        }, function(Ex) {
            callbackError(Ex);
        });
  
    }
    
    function getDataByECcodeAndItemId(ecsite_code, item_id, callbackSuccess, callbackError) {
        DetailProductService.prototype.getItemInfo({action: "prodbyitemid", eccode: ecsite_code, itemid: item_id}, function(data) {
            var items = data.items;
            if(items.length > 0) {
                var dataItem = {};
                dataItem.item_name = items[0].itemName;
                dataItem.shop_name = items[0].shopName;
                dataItem.shop_url = items[0].itemUrl;
                dataItem.ecsite_code = ""+items[0].ecSiteCode;
                dataItem.lowestPrice = items[0].formattedItemPrice;
                if(typeof items[0].smallImageUrl != "undefined") {
                    dataItem.image_url = items[0].smallImageUrl;
                } else {
                    dataItem.image_url = Messages.prototype.NO_IMAGE;
                }
        
                var genreOri = items[0].genreIdOriginal;
                DetailProductService.prototype.getGenreByGenreIdOriginal(ecsite_code, genreOri, function(genreData) {
                    dataItem.genre_code = genreData.code;
                    callbackSuccess(dataItem);
                }, function() {
                    callbackSuccess(dataItem); 
                });
            } else {
                callbackError();
            }   
        }, callbackError); 
    }
    
    function displayDetailProductPage(dataItem) {
        $("#pageNoResult").hide();
        $("#ECshop").hide();        

        var star_clicked = (currentData.typeAction == 0) ? "star_clicked"  : "";
        var checkStar = '<span id="star_checkbox_detailpage" class="' + star_clicked + '">&#9733;</span>';
        $('#productName').html(dataItem.item_name);
        
        var imageUrl = '<img src = "' + dataItem.image_url + '" width="64px" height="64px" /> ';
        var lowestProductInfo = "最安値: <span class='price'>" + dataItem.lowestPrice + "円</span><p class='shopname'>" + dataItem.shop_name + "</p>" ; 
        var html = "<li><a href='#' class = 'shopDetailWebLink' web_url= '" + dataItem.shop_url + "'>" + lowestProductInfo +  imageUrl + "</li></a>"; 
        $("#oneProductInfor").html('').append(html).listview("refresh");
        
        if(currentData.searchKindAction == 0) { // barcode so display list EC data items
            $("#pageResult").show();
            $("#ECshop").show();

            var listEClength = dataItem.ECShop.length;
            var list = '';
            if(listEClength > 0) {
                for(var i=0; i<listEClength; i++) {
                    var shopName = DetailProductService.prototype.getEcNameByECcode(dataItem.ECShop[i].ecsite_code);
                    var itemNumber = dataItem.ECShop[i].numberOfItems;
                    var ecCode = dataItem.ECShop[i].ecsite_code;
                    var shopImage = "";
                    if(ecCode == 10) {
                        shopImage = "<img src = 'images/icons/rakuten.jpg' />";
                    }    
                    var shop_count =  (itemNumber <= 1) ? "" : "<span class='ui-li-count'>" + itemNumber +"</span>";
                    //list += "<li><a href='#' class = 'shopLink' id='" + dataItem.ECShop[i].ecsite_code + "'>" + shopName + " <div>最安値: <span class='price'>" + dataItem.ECShop[i].lowestPrice + "円</span></div>" + shop_count + shopImage + "</li></a>";
                    list += "<li><a href='#' class = 'shopLink' id='" + dataItem.ECShop[i].ecsite_code + "'>" + shopName + "<br /><span style = 'font-weight:normal'>&nbsp;&nbsp;最安値: <span style = 'color:red;text-decoration: underline;'>" + dataItem.ECShop[i].lowestPrice + "円</span></span>" + shop_count  + "</a></li>";
                }
            } else {
                list = "<h3 class='no-item'>販売店が見つかりませんでした</h3>";
            }
            $("#listEC").html('').append(list).listview('refresh');
        }
        $("#star-link").html(checkStar);
        $("#add-to-atodekau").text((currentData.typeAction == 0) ? "ブックマークを編集する" : "ブックマークする");
        $("#add-to-atodekau").show();

        Util.prototype.hideSpinner(); 
    }
    
    function displayNoResultData(barcode) {        
        var list = (typeof barcode !== 'undefined') ? 
                        "<h3>バーコード番号：" + barcode +" に一致する商品は見つかりませんでした</h3>" :
                        "<h3>商品は見つかりませんでした</h3>";
        $("#pageNoResult").html(list);
        $("#pageResult").hide();
        $("#pageNoResult").show();
        Util.prototype.hideSpinner();
    }
    
    $(document).on('tap','#add-to-atodekau',function() {
        Util.prototype.showSpinner();
        
        var typeAction = currentData.typeAction;
        var params = {};
        if(typeAction == 0 || typeAction == 1 ) { // bookmarked //scanned
            params = {"action" : ((typeAction == 0) ? 0 : 1), "bm_id" : currentData.id};
        } else if(typeAction == 11) {
            params = {"action" : ((typeAction == 0) ? 0 : 1), "bm_id" : currentData.id, "scanAction": true};
        } else if(typeAction == 2) { // new
            var today = Util.prototype.getTodayObj();
            params = {"action" : 2, 
                        "item_id" : currentData.item_id,
                        "item_name" : currentData.dataItem.item_name,
                        "image_url" : currentData.dataItem.image_url,
                        "genre_code" : currentData.dataItem.genre_code,
                        "ecsite_code" : currentData.dataItem.ecsite_code,
                        "registered_date" : today.ymd,
                        "registered_month" : today.m, "registered_year" : today.y };
        }
        PageChangeController.prototype.changeToPage('pageBookmarkRegister', params);
    });
    
    $(document).on("tap","#listEC a",function(){  
        Util.prototype.showSpinner();

        var params = {'firstClickedEcCode': $(this).attr("id"),
                        'ecShops': currentData.dataItem.ECShop,
                        'barcode_number': currentData.barcode_number};

        PageChangeController.prototype.changeToPage('pageECsite', params);
    });  
    
    $(document).on("tap", "#star_checkbox_detailpage", function() {
        $(this).toggleClass("star_clicked");
        var bmId =  currentData.id,
            isExistBmId = (typeof currentData.id != "undefined" && currentData.id != "");
        if (isExistBmId && currentData.typeAction == 0) { // bookmarked
            if(currentData.searchKindAction == 0) {
                Util.prototype.showSpinner('削除しています');
                BookmarksService.prototype.deleteAdvanceBookmark(null, [{id: bmId, status: '0'}], function() {
                    $("#add-to-atodekau").text("ブックマークする");
                    currentData.typeAction = 1;
                    Util.prototype.hideSpinner();
                });
            } else {
                Util.prototype.showSpinner();
                BookmarksService.prototype.deleteAdvanceBookmark([bmId], null, function() {
                    $("#add-to-atodekau").text("ブックマークする");
                    currentData.id = '';
                    currentData.typeAction = 2;
                    Util.prototype.hideSpinner();
                });
            }
        } else if (isExistBmId) { // scanned
            Util.prototype.showSpinner('ブックマークしています');
            console.log("from scan to bm: " + bmId);
            BookmarksService.prototype.saveScanBookmark(bmId, {id: bmId, saveLogType: DetailProductService.prototype.SERVER_LOG_BOOKMARK, status: '2'}, function() {
                $("#add-to-atodekau").text("ブックマークを編集する");
                currentData.typeAction = 0;
                Util.prototype.hideSpinner();
            });
        } else { // new
            Util.prototype.showSpinner('ブックマークしています');
            var param = {};
            param.status = 1;
            var today = Util.prototype.getTodayObj();
            param.registered_date = today.ymd;
            param.registered_month = today.m;
            param.registered_year = today.y;
            param.genre_code = currentData.dataItem.genre_code;
            param.image_url = currentData.dataItem.image_url;
            param.ecsite_code = "" + currentData.dataItem.ecsite_code;
            param.item_name = currentData.dataItem.item_name;
            param.saveLogType = DetailProductService.prototype.SERVER_LOG_BOOKMARK;
            
            if(currentData.searchKindAction == 0) {
                param.barcode_number = currentData.barcode_number;
            } else { 
                param.item_id = currentData.item_id;  
            }
            if(typeof param.image_url == "undefined" || param.image_url == "") {
                param.image_url = Messages.prototype.NO_IMAGE;
            }
            BookmarksService.prototype.saveScanBookmark('', param, function(saveId) {
                currentData.id = saveId;
                currentData.typeAction = 0;
                $("#add-to-atodekau").text("ブックマークを編集する");
                Util.prototype.hideSpinner();
            });
        }
    });
    
    DetailProductController.prototype.freeMemory = function(isPageHome) {
        $('#productName').text('');
        $("#oneProductInfor").html('').listview("refresh");
        $("#listEC").html('').listview("refresh");
        innerParams = null;
        currentData = null;
        if (isPageHome) {
            DetailProductController.prototype.params = null;
        }
    };
});